package com.unipay.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unipay.common.handler.UnipayException;
import com.unipay.common.helper.HttpRequestHelper;
import com.unipay.common.helper.JwtHelper;
import com.unipay.common.rabbit.constant.MqConst;
import com.unipay.common.rabbit.service.RabbitService;
import com.unipay.common.result.ResultCodeEnum;
import com.unipay.common.utils.MD5;
import com.unipay.enums.OrderStatusEnum;
import com.unipay.hosp.client.HospitalFeignClient;
import com.unipay.model.order.OrderInfo;
import com.unipay.model.user.Patient;
import com.unipay.order.mapper.OrderMapper;
import com.unipay.order.service.OrderService;
import com.unipay.order.service.WeixinService;
import com.unipay.user.client.PatientFeignClient;
import com.unipay.vo.hosp.ScheduleOrderVo;
import com.unipay.vo.msm.MsmVo;
import com.unipay.vo.order.*;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @Project: yitong_parent
 * @Author: Chenmy
 * @Time: 2023-07-04 21:02:59
 * @Desc: TODO
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderInfo> implements OrderService {

    @Autowired
    private PatientFeignClient patientFeignClient;
    @Autowired
    private HospitalFeignClient hospitalFeignClient;
    @Autowired
    private WeixinService weixinService;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private OrderMapper orderMapper;

    // 预约下单，保存订单
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long saveOrder(String scheduleId, Long patientId, HttpServletRequest request) {
        // TODO 获取：用户ID
        String token = request.getHeader("token");
        Long userId = JwtHelper.getUserId(token);

        Patient patient = patientFeignClient.getPatient(patientId);
        if (null == patient) {
            throw new UnipayException(ResultCodeEnum.PARAM_ERROR);
        }
        ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVo(scheduleId);
        System.out.println("scheduleOrderVo: " + scheduleOrderVo);
        if (null == scheduleOrderVo) {
            throw new UnipayException(ResultCodeEnum.PARAM_ERROR);
        }
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(scheduleOrderVo.getHoscode());
        if (null == signInfoVo) {
            // 签名错误
            throw new UnipayException(ResultCodeEnum.SIGN_ERROR);
        }
        // 当前时间不可预约
        // if (new DateTime(scheduleOrderVo.getStartTime()).isAfterNow() || new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()) {
        //     throw new UnipayException(ResultCodeEnum.TIME_NO);
        // }
        // 号源不足
        if (scheduleOrderVo.getAvailableNumber() <= 0) {
            throw new UnipayException(ResultCodeEnum.NUMBER_NO);
        }

        // 1、用户端，数据库更新数据
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        BeanUtils.copyProperties(scheduleOrderVo, orderInfo);
        // 向order中，设置其他数据
        String outTradeNo = System.currentTimeMillis() + "" + new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTradeNo);
        // orderInfo.setScheduleId(scheduleId);
        orderInfo.setScheduleId(scheduleOrderVo.getHosScheduleId());
        orderInfo.setPatientId(patientId);
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        // this.save(orderInfo);    ??????
        baseMapper.insert(orderInfo);

        // 1、管理端，封装数据传参
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode", orderInfo.getHoscode());
        paramMap.put("depcode", orderInfo.getDepcode());
        paramMap.put("hosScheduleId", orderInfo.getScheduleId());
        paramMap.put("reserveDate", new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount", orderInfo.getAmount());
        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType", patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex", patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone", patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode", patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode", patient.getDistrictCode());
        paramMap.put("address", patient.getAddress());
        //联系人
        paramMap.put("contactsName", patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo", patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone", patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        // TODO 获取签名，发送请求
        // String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        String sign = MD5.encrypt(signInfoVo.getSignKey());
        paramMap.put("sign", sign);
        // 返回jsonObject格式数据
        // TODO ------?????-------http://localhost:8201/order/submitOrder，改为manage端9998端口
        // JSONObject result = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl() + "/order/submitOrder");
        String originURL = signInfoVo.getApiUrl();
        String magURL = originURL.split(":")[0] + ":" + originURL.split(":")[1] + ":" + "9998";
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, magURL + "/order/submitOrder");
        if (result.getInteger("code") == 200) {
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");
            ;
            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");
            ;
            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");
            ;
            // TODO 更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            baseMapper.updateById(orderInfo);
            //排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");

            // TODO 发送mq信息，更新号源和短信通知 -------------
            // （1）发送mq消息，更新数据源
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setAvailableNumber(availableNumber);
            orderMqVo.setReservedNumber(reservedNumber);
            // （2）短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            Map<String, Object> param = new HashMap<String, Object>() {{
                put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                put("amount", orderInfo.getAmount());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
                put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
            }};
            msmVo.setParam(param);
            orderMqVo.setMsmVo(msmVo);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
        } else {
            throw new UnipayException(result.getString("message"), result.getInteger("code"));
            // throw new UnipayException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
        return orderInfo.getId();
    }

    @Override
    public IPage<OrderInfo> selectPage(Page<OrderInfo> orderInfoPage, OrderQueryVo orderQueryVo) {
        QueryWrapper<OrderInfo> orderInfoQueryWrapper = orderQueryVo.buildQueryWrapper();
        Page<OrderInfo> pages = baseMapper.selectPage(orderInfoPage, orderInfoQueryWrapper);
        // TODO 编号变成对应值封装
        pages.getRecords().stream().forEach(
                item -> {
                    this.packOrderInfo(item);
                }
        );
        return pages;
    }

    @Override
    public OrderInfo getOrderById(Long orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        this.packOrderInfo(orderInfo);
        return orderInfo;
    }

    private OrderInfo packOrderInfo(OrderInfo orderInfo) {
        orderInfo.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }

    // 取消订单
    @Override
    public Boolean cancelOrder(Long orderId) {
        //（1）获取订单信息，判断是否取消
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        // TODO 当前时间大约退号时间，不能取消预约
        DateTime quitTime = new DateTime(orderInfo.getQuitTime());
        // if (quitTime.isBeforeNow()){
        //     throw new UnipayException(ResultCodeEnum.CANCEL_ORDER_NO);
        // }
        //（2）调用医院接口，发送请求，实现预约取消
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode());
        if (null == signInfoVo){
            throw new UnipayException(ResultCodeEnum.SIGN_ERROR);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("hoscode", orderInfo.getHoscode());
        map.put("hosRecordId", orderInfo.getHosRecordId());
        map.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = MD5.encrypt(signInfoVo.getSignKey());
        map.put("sign", sign);
        String originURL = signInfoVo.getApiUrl();
        String magURL = originURL.split(":")[0] + ":" + originURL.split(":")[1] + ":" + "9998";
        JSONObject result = HttpRequestHelper.sendRequest(map, magURL + "/order/updateCancelStatus");
        //（3）根据医院接口，返回数据
        if (result.getInteger("code") != 200){
            throw new UnipayException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }else {
            // TODO 判断当前订单是否可以取消-------是否支付
            if (orderInfo.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus()){
                // TODO 调用微信接口，判断：是否退款成功
                Boolean refund = weixinService.refund(orderId);
                if (!refund){
                    throw new UnipayException(ResultCodeEnum.CANCEL_ORDER_FAIL);
                }
                // 更新订单状态
                orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
                baseMapper.updateById(orderInfo);
                // 发送mq更新预约数量
                // 我们与下单成功更新预约数使用相同的mq信息，不设置可预约数与剩余预约数，接收端可预约数减1即可，TODO mq监听器HospitalReceiver实现
                OrderMqVo orderMqVo = new OrderMqVo();
                orderMqVo.setScheduleId(orderInfo.getScheduleId());
                // 短信提示
                MsmVo msmVo = new MsmVo();
                msmVo.setPhone(orderInfo.getPatientPhone());
                msmVo.setTemplateCode("SMS_460755565");
                String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
                Map<String, Object> param = new HashMap<>();
                param.put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                param.put("reserveDate", reserveDate);
                param.put("name", orderInfo.getPatientName());
                msmVo.setParam(param);
                orderMqVo.setMsmVo(msmVo);
                rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
            }
        }
        return true;
    }
    // 就诊提醒
    @Override
    public void patientTips() {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        // queryWrapper.eq("reserve_date", new DateTime().toString("yyyy-MM-dd"));
        queryWrapper.eq("reserve_date", "2021-01-28");
        queryWrapper.ne("order_status", OrderStatusEnum.CANCLE.getStatus());
        List<OrderInfo> orderInfoList = baseMapper.selectList(queryWrapper);
        //短信提示
        for(OrderInfo orderInfo : orderInfoList){
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(param);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        }
    }

    // 获取：订单统计信息
    @Override
    public Map<String, Object> getCountMap(OrderCountQueryVo orderCountQueryVo) {
        HashMap<String, Object> map = new HashMap<>();
        // 日期,列表
        // List<OrderCountVo> orderCountVoList = baseMapper.selectOrderCount(orderCountQueryVo);
        List<OrderCountVo> orderCountVoList = orderMapper.selectOrderCount(orderCountQueryVo);
        List<String> dateList = orderCountVoList.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
        // 统计,列表
        List<Integer> countList = orderCountVoList.stream().map(OrderCountVo::getCount).collect(Collectors.toList());
        map.put("dateList", dateList);
        map.put("countList", countList);
        System.out.println(map);
        // {countList=[1, 2, 2], dateList=[2021-01-22, 2021-01-23, 2021-01-28]}
        return map;
    }
}
